package com.gwcm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwcm.exception.BusinessException;
import com.gwcm.mapper.MenuMapper;
import com.gwcm.mapper.RoleMenuMapper;
import com.gwcm.mapper.UserMapper;
import com.gwcm.model.dto.role.RoleQueryRequest;
import com.gwcm.model.entity.*;
import com.gwcm.model.vo.*;
import com.gwcm.service.IRoleService;
import com.gwcm.mapper.RoleMapper;
import com.gwcm.util.PageUtil;
import com.yhz.commonutil.common.ErrorCode;
import com.yhz.commonutil.constant.SortConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 15375
* @description 针对表【role(角色表)】的数据库操作Service实现
* @createDate 2023-03-21 16:40:11
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements IRoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuMapper menuMapper;
    @Override
    public List<String> getRolesByUserName(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper);
        List<Role> roleList = this.baseMapper.getRolesByUserId(user.getId());
        List<String> roleNameList = roleList.stream().map(role -> role.getRoleName()).collect(Collectors.toList());
        if (CollUtil.isEmpty(roleList)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return roleNameList;
    }

    @Override
    public boolean attachRoleByUserId(Long roleId, Long userId) {
        int result = 0;
        try{
            result = this.baseMapper.attachRoleByUserId(roleId, userId);
        }catch (Exception e){
            log.error("method[attachRoleByUserId] fail,msg:{}",e);
            throw new BusinessException(ErrorCode.SAVE_ERROR);
        }

        return result == 1;
    }

    /**
     * 角色分页查询
     * @param roleQueryRequest 查询条件
     * @return
     * @throws BusinessException
     */
    @Override
    public IPage<RoleVo> pageList(RoleQueryRequest roleQueryRequest) throws BusinessException {
        IPage<Role> page = PageUtil.vaildPageParam(roleQueryRequest.getCurrent(), roleQueryRequest.getPageSize());
        String sortField = roleQueryRequest.getSortField();
        String sortOrder = roleQueryRequest.getSortOrder();

        if (StrUtil.isBlank(sortOrder) || !StrUtil.equalsAny(sortOrder, SortConstant.SORT_ORDER_ASC, SortConstant.SORT_ORDER_DESC)) {
            //默认按升序排序
            sortOrder = SortConstant.SORT_ORDER_ASC;
        }
        roleQueryRequest.setSortField(sortField);
        roleQueryRequest.setSortOrder(sortOrder);
        IPage<RoleVo>  roleToIPage = roleMapper.selectRoleToPage(page, roleQueryRequest);
        IPage<RoleVo>  roleVoIPage =  roleToIPage.convert(item -> {
            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(item, roleVo);
            return roleVo;
        });

        return roleVoIPage;
    }

    /**
     * 根据id查询role
     *
     * @param roleId
     * @return
     */
    public RoleVo selectRoleById(Long roleId){
        Role role = roleMapper.selectRoleById(roleId);
        List<Menu> menuList = selectRoleMenu(roleId);
        RoleMenuVo roleMenuVo = new RoleMenuVo();
        roleMenuVo.setMenuList(menuList);
        RoleVo roleVo = new RoleVo();
        roleVo.setRoleMenuVo(roleMenuVo);
        BeanUtils.copyProperties(role, roleVo);
        return roleVo;
    }

    /**
     * 查询角色的菜单
     * @param roleId
     * @return
     */
    public List<Menu> selectRoleMenu(Long roleId){
        List<Menu> list = menuMapper.selectMenusByRoleId(roleId);
        if(list.size() > 0){
            return list;
        } else {
            return null;
        }
    }

    /**
     * 查询role列表
     * @param role
     * @return
     */
    public List<Role> selectRoleList(Role role){
        return roleMapper.selectRoleList(role);
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    public int deleteRoleById(Long roleId){
        return roleMapper.deleteRoleById(roleId);
    }

    /**
     * 新增角色
     * @param role
     */
    @Override
    public void saveRole(Role role) {
        String roleName = role.getRoleName();
        String roleKey = role.getRoleKey();
//        System.out.println(roleName);
//        System.out.println(roleKey+"角色权限字符串");
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("role_name", roleName);
        Role selectOne = baseMapper.selectOne(roleQueryWrapper);
        if (!ObjectUtil.isEmpty(selectOne) || checkRoleKeyUnique(roleKey)) {
            throw new BusinessException("角色名称或角色权限已存在", 50000, "");
        }
        int insert = baseMapper.insert(role);
        if (insert < 1) {
            throw new BusinessException(ErrorCode.SAVE_ERROR);
        }
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    public void updateRole(Role role) {
        String roleName = role.getRoleName();
        String roleKey = role.getRoleKey();
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("role_name", roleName);
        Role selectOne = baseMapper.selectOne(roleQueryWrapper);
        if (!ObjectUtil.isEmpty(selectOne) || checkRoleKeyUnique(roleKey)) {
            throw new BusinessException("角色名称或角色权限已存在", 50000, "");
        }
        int update = baseMapper.updateById(role);
        if (update < 1) {
            throw new BusinessException(ErrorCode.UPDATE_ERROR);
        }
    }

    /**
     * 检查角色权限字符串是否唯一
     * @param roleKey
     * @return
     */
    public boolean checkRoleKeyUnique(String roleKey){
        Role role = roleMapper.checkRoleKeyUnique(roleKey);
        if(role != null){
            return true;
        }else {
            return false;
        }
//        return count > 0 ? true : false;
    }

    /**
     * 新增角色菜单组信息
     * @param roleId 角色ID
     * @param menuIds 菜单组
     */
    public void insertRoleMenu(Long roleId, Long[] menuIds) {
        if(menuIds.length > 0){
            //新增角色与菜单管理
            List<RoleMenu> list = new ArrayList<RoleMenu>();
            for(Long menuId : menuIds){
                RoleMenu rm = new RoleMenu();
                rm.setRoleId(roleId);
                rm.setMenuId(menuId);
                rm.setCreateTime(new Date());
                rm.setUpdateTime(new Date());
                list.add(rm);
            }
            if(list.size() > 0){
                roleMenuMapper.batchRoleMenu(list);
            }
        }
    }

    /**
     * 角色菜单授权
     * @param roleId
     * @param menuIds
     */
    public void insertRoleAuth(Long roleId, Long[] menuIds){
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        insertRoleMenu(roleId, menuIds);
    }
}




